package com.xqboss.apps.service.game;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xqboss.apps.domain.game.Game;
import com.xqboss.apps.dto.PageDto;
import com.xqboss.apps.dto.game.GameDto;
import com.xqboss.apps.enums.game.GameCodeEnum;
import com.xqboss.apps.mapper.game.GameMapper;
import com.xqboss.apps.vo.game.materialStrike.GameVo;
import com.xqboss.common.constant.CacheConstants;
import com.xqboss.common.core.domain.R;
import com.xqboss.common.core.domain.entity.SysDictData;
import com.xqboss.common.core.redis.RedisCache;
import com.xqboss.common.exception.ServiceException;
import com.xqboss.common.utils.DictUtils;
import com.xqboss.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class GameService extends ServiceImpl<GameMapper,Game> {

    @Autowired
    private RedisCache redisCache;

    /**
     * app - 获取没有隐藏的游戏列表，并排序
     *
     * @return List<GameVo>
     */
    public R<List<GameVo>> gameList(Long userId) {
        List<GameVo> gameVos = redisCache.getCacheObject(CacheConstants.GAME_LIST);
        if (CollUtil.isEmpty(gameVos)) {
            List<Game> games = this.lambdaQuery().eq(Game::getIsHidden, "0").orderByAsc(Game::getSort).list();
            Assert.isTrue(CollUtil.isNotEmpty(games),()->new ServiceException("还未配置游戏列表数据~"));
            gameVos = BeanUtil.copyToList(games, GameVo.class);
            redisCache.setCacheObject(CacheConstants.GAME_LIST,gameVos);
        }
        gameVos.forEach(g->g.setIsAuth(verifyUserId(g.getGameCode(),userId)));
        return R.ok(gameVos,"获取游戏列表成功~");
    }



    /**
     * 定时任务-开启、关闭游戏
     *
     * @param gameId 游戏id，不传更新所有游戏的开启、关闭状态
     * @param isOpen 0：关闭，1：开启
     */
    public void operateStatus(Long gameId, int isOpen) {
        String msg = isOpen==0?"关闭":"开启";
        if (gameId==null) {
            this.lambdaUpdate().set(Game::getIsOpen, isOpen).update();
            log.info("所有游戏的"+msg+"成功~");
        }else{
            Game game = this.getById(gameId);
            Assert.notNull(game,()->new ServiceException("游戏不存在~"));
            game.setIsOpen(isOpen);
            this.updateById(game);
            log.info("游戏["+game.getName()+"]"+msg+"成功~");
        }
        redisCache.deleteObject(CacheConstants.GAME_LIST);
    }


    /**
     * description: 校验用户是否具有权限
     *
     * @param gameCode 游戏标识 ；avoidFrogExplain-躲避调皮蛙 ；getABreakExplain-时来运转 ；friedNewYearBeastExplain-炸年兽
     * @param userId 用户id
     * @author ljh
     *
     * @return true-有权访问（未配置白名单 或 是白名单用户）
     */
    public Boolean verifyUserId(GameCodeEnum gameCode, Long userId) {
        List<SysDictData> data = DictUtils.getDictCache(gameCode.getDictType());
        if (data == null) {
            return Boolean.TRUE;
        }
        boolean isAllStop = data.stream().allMatch(d -> Objects.equals(d.getStatus(), "1"));
        if (isAllStop) {
            return Boolean.TRUE;
        }
        return data.stream().anyMatch(d->d.getDictValue().equals(String.valueOf(userId)) && Objects.equals(d.getStatus(),"0"));
    }

    /**
     * web - 获取没有隐藏的游戏列表，并排序
     *
     * @return List<Game>
     */
    public IPage<Game> webGameList(PageDto dto,String name) {
        Page<Game> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        LambdaQueryWrapper<Game> wrapper = Wrappers.lambdaQuery(Game.class)
                .like(StringUtils.isNotEmpty(name), Game::getName, name)
                .orderByAsc(Game::getSort);
        return this.page(page,wrapper);
    }

    /**
     * web - 新增或编辑游戏
     *
     * @param dto
     * @return
     */
    public R<String> saveOrEdit(GameDto dto) {
        this.lambdaQuery().ne(dto.getId()!=null,Game::getId,dto.getId()).eq(Game::getName,dto.getName()).oneOpt().ifPresent(g->{
            throw new ServiceException(String.format("游戏名为[%s]的游戏已存在~",g.getName()));
        });
        Game game = BeanUtil.toBean(dto, Game.class);
        boolean sou = this.saveOrUpdate(game);
        Assert.isTrue(sou,()->new ServiceException(String.format("%s失败~",dto.getId()==null?"新增":"修改")));
        redisCache.deleteObject(CacheConstants.GAME_LIST);
        return R.ok_msg(String.format("%s成功~",dto.getId()==null?"新增":"修改"));
    }

    /**
     * web - 删除游戏
     *
     * @param gameId 游戏id
     * @return
     */
    public R<String> delete(Long gameId) {
        Assert.notNull(gameId,"游戏id不能为空~");
        this.lambdaQuery().eq(Game::getId,gameId).oneOpt().ifPresent(g->{
            if (g.getIsOpen()==1) {
                throw new ServiceException(String.format("游戏[%s]为开启状态不能删除~",g.getName()));
            }
        });
        boolean b = this.removeById(gameId);

        return R.ok_msg(String.format("删除%s~",b?"成功":"失败"));
    }
}
